var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;

let startTime = 0;
let endTime = 0;
function getNowMonth() {
    $.ajax({
        async:false,
        type: 'POST',
        url: 'number/getNowMonthNew',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if (res.data != "") {
                    startTime = res.data.startDate;
                    endTime = res.data.endDate;
                }
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        },
        error: function (data) {
            layer.msg(data.msg, {icon: 5});
        }
    });
}

getNowMonth();

let endDate= laydate.render({
    elem: '#endCreateTime',//选择器结束时间
    type: 'date',
    value : new Date(endTime),
    min:"1970-1-1",//设置min默认最小值
    done: function(value,date){
        startDate.config.max={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        }
    }
});

let startDate=laydate.render({
    elem: '#startCreateTime',
    type: 'date',
    value : new Date(startTime),
    max:"2099-12-31",//设置一个默认最大值
    done: function(value, date){
        endDate.config.min ={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        };
    }
});

layui.use(['tableEdit',"excel"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel;

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    let colourList = getdictionary(6, 41);//颜色
    let unitList = getdictionary(6, 42);//单位
    let currencyList = getdictionary(5,14);//币种
    $.each(currencyList, function (index, item) {
        $("#currency").append(new Option(item.name, item.code));
    });
    //签约单位
    let complaintUnit = [];
    $.ajax({
        url: "company/getAllMakerUnit",
        success: function (res) {
            if (res.status == 200) {
                complaintUnit = res.data;
                //制单公司
                $.each(complaintUnit, function (index, item) {
                    $("#complaintUnit").append(new Option(item.name, item.code));
                });
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    let userList = [];//操作人

//操作员、业务员
    $.ajax({
        type : 'POST',
        url:'user/getAllUserNameAndCode',
        dataType:"json",
        contentType: 'application/json;charset=utf-8',
        success:function(res){
            if(res.status == 200){
                if(res.data){
                    userList = res.data;
                }else{
                    layer.msg(res.msg,{icon:0});
                }
            }else{
                layer.msg(res.msg,{icon:4});
            }
        }
    });
    let operationList=[];
    let salesmanList=[];
    layer.ready(function () {
        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList=getxmselect("#executor", "executor", userTree);
            salesmanList=getxmselect("#salesman", "salesman", userTree);
        } else {
            operationList=getxmselect("#executor", "executor", [{name: user.name, value: user.code}]);
            salesmanList=getxmselect("#salesman", "salesman", [{name: user.name, value: user.code}]);
        }

        //单据信息
        let boxStatusArr = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2"},
            {name: "已批箱", value: "3"},
            {name: "完成箱", value: "4"},
            {name: "垃圾箱", value: "5"}
        ];
        getxmselect("#boxStatus", "boxStatus", boxStatusArr);

        table.render({
            elem: '#customercomplaintselect'
            ,url: 'complaint/selectMainAndProductList'
            ,method:'post'
            ,request: {
                pageName: 'pageNum'
                ,limitName: 'pageSize'
            }
            ,contentType: 'application/json;charset=utf-8'
            ,toolbar: '#customercomplainttoolbar'
            ,id: 'customercomplainttableid'
            ,cellMinWidth: 120
            ,totalRow: true
            ,cols: [[
                {checkbox: true}
                ,{field:'oddNumber',width:170, title:'客诉单号',sort:true,event: "customercomplaintnumber"}
                ,{field:'createTime', title:'创建日期',sort:true,width: 185,templet: function(d) {return layui.util.toDateString(d.createTime,"yyyy-MM-dd");}}
                ,{field:'responsibleParty', title:'责任方'}
                ,{field:'complaintUnit', title:'制单公司',
                    templet: function(data) {
                        let name = "";
                        $.each(complaintUnit, function(index, item) {
                            if (data.complaintUnit==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        if (name==""){
                            name = data.complaintUnit;
                        }
                        return name;
                    }
                }
                ,{field:'customerName', title:'客户名称'}
                ,{field:'executor', title:'操作员',
                    templet: function(data) {
                        let name = "";
                        $.each(userList, function(index, item) {
                            if (data.executor==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        return name;
                    }
                }
                ,{field:'salesman', title:'业务员',
                    templet: function(data) {
                        let name = "";
                        $.each(userList, function(index, item) {
                            if (data.salesman==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        return name;
                    }
                },
                {field: 'contractNo', title: '销售合同号', sort: true,style:"overflow:hidden"},
                {field: 'customerArticleNo', title: '销售合同号', sort: true,style:"overflow:hidden",hide: true},
                {field: 'productNo', title: '产品编码', sort: true,style:"overflow:hidden"},
                {field: 'clientDeductionPrice', title: '客户扣款金额', sort: true,style:"overflow:hidden", totalRow: true},
                {field: 'supplierDeductionPrice', title: '供应商扣款金额', sort: true,style:"overflow:hidden", totalRow: true},
                {field:'isEstablish', title:'客诉成立否', templet: function(d) {return d.isEstablish==1?"是":"否";}}
                ,{field:'currency', title:'币种',
                    templet: function(data) {
                        let name = "";
                        $.each(currencyList, function(index, item) {
                            if (data.currency==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        return name;
                    }
                }
                ,{field:'boxStatus', title:'单据类型', templet: function(data) {
                        switch (data.boxStatus) {
                            case "1": return "草稿箱";
                            case "2": return "待批箱";
                            case "3": return "已批箱";
                            case "4": return "完成箱";
                            case "5": return "垃圾箱";
                        }
                    }
                },
                {field: 'productId', title: '客诉产品id', hide:true},
                {field: 'specNo', title: '规格编码', sort: true,style:"overflow:hidden"},
                {field: 'normExplain', title: '规格说明',style:"overflow:hidden"},
                {field: 'chineseName', title: '中文名称',style:"overflow:hidden"},
                {field: 'englishName', title: '英文名称',style:"overflow:hidden"},
                {field: 'chineseDesc', title: '中文描述',style:"overflow:hidden"},
                {field: 'englishDesc', title: '英文描述',style:"overflow:hidden"},
                {field: 'colour', title: '颜色',
                    templet: function(data) {
                        let name = "";
                        $.each(colourList, function(index, item) {
                            if (data.colour==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        if(data.colour){
                            if(name==""){
                                name = data.colour;
                            }
                        }
                        return name;
                    }
                },
                {field: 'unit', title: '单位',
                    templet: function(data) {
                        let name = "";
                        $.each(unitList, function(index, item) {
                            if (data.unit==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        if(data.unit){
                            if(name==""){
                                name = data.unit;
                            }
                        }
                        return name;
                    },
                },
                {field: 'price', title: '单价', totalRow: true,
                    templet: function (d) {
                        return d.price?Number(d.price).toFixed(4):Number(0).toFixed(4);
                    }
                },
                {field: 'remark', title: '备注',style:"overflow:hidden"},
                {field: 'amount', title: '数量', totalRow: true,
                    templet: function (d) {
                        return d.amount?Number(d.amount).toFixed(2):Number(0).toFixed(2);
                    }
                },
                {field: 'priceSubtotal',width:120, title: '小计',
                    templet: function(d) {
                        if(d.amount==undefined || d.price==undefined){return 0.00;}
                        return (d.amount*d.price).toFixed(2);
                    },
                },
            ]]
            ,height: $(document).height() - $('#customercomplaintselect').offset().top - 50
            , limit: 50
            , limits: [50, 100, 200,500,1000]
            ,page: true
            ,parseData: function(res){
                let code = 0 , count = 0, data = null;
                if(res.status!=200 &&res.status!=0){
                    layer.msg(res.msg);
                }else{
                    code = res.status;
                    count = res.total;
                    data = res.data;
                }
                return {
                    "code": code,
                    "count": count,
                    "data": data
                }
            }
        });

    });
    form.render();//表单刷新
    document.getElementById('clear').onclick = function(){
        operationList.setValue([ ]);
        salesmanList.setValue([ ]);
    };
    form.on('submit(submitform)', function(data){
        table.reload('customercomplainttableid',{where: data.field });
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            url:"complaint/export/selectMainAndProductList",
            data: queryReq.field,
            success: function(res) {
                if(res.status == 200){
                    let excelData = res.data.data;
                    if(excelData){
                        $.each(excelData,function (n, item){
                            //制单公司
                            item = excelDataProcess(complaintUnit,item,3);
                            //操作员
                            item = excelDataProcess(userList,item,5);
                            //业务员
                            item = excelDataProcess(userList,item,6);
                            //颜色
                            item = excelDataProcess(colourList,item,17);
                        })
                    }
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: excelData
                    }, '客诉产品详情列表.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });


    function excelDataProcess(queryList,item,cursor){
        let res = item;
        if(queryList){
            if(res){
                let name = "";
                $.each(res,function (n, cc){
                    if(n==cursor){
                        $.each(queryList, function(m, cu) {
                            if (cc==cu.code){
                                name = cu.name;
                                return ;
                            }
                        });
                        //不在查询列表的数据 显示原数据
                        if (name==""){
                            name = cc;
                        }
                        // console.log(name)
                    }
                })
                res[cursor] = name;
            }else{
                console.log("暂无数据")
            }
        }else{
            console.log("查询列表暂无数据")
        }
        return res;
    }
});